package com.hudage.kotlinmvp.ui.fragment

import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentPagerAdapter
import androidx.viewpager.widget.ViewPager
import com.google.android.material.tabs.TabLayout
import com.hudage.kotlinmvp.R
import com.hudage.kotlinmvp.base.BaseFragment
import com.hudage.kotlinmvp.mvp.contract.DiscoveryContract
import com.hudage.kotlinmvp.mvp.model.bean.DiscoveryBean
import com.hudage.kotlinmvp.mvp.presenter.DiscoveryPresenter
import com.hudage.kotlinmvp.ui.adapter.MyPagerAdapter
import com.orhanobut.logger.Logger

open class DiscoveryFragment : BaseFragment(), DiscoveryContract.View {

    private lateinit var tabLayoutDiscovery: TabLayout
    private lateinit var viewPagerDiscovery: ViewPager
    private lateinit var adapter: MyPagerAdapter

    private var fragments = ArrayList<Fragment>()
    private var titles = ArrayList<String>()

    private val mPresenter by lazy {
        DiscoveryPresenter()
    }

    companion object {
        fun getInstance(): DiscoveryFragment {
            val fragment = DiscoveryFragment()
            val bundle = Bundle()
            fragment.arguments = bundle
            return fragment
        }
    }

    override fun getLayoutId(): Int = R.layout.fragment_discovery_layout

    override fun initView() {
        mPresenter.attachView(this)
        mPresenter.getDiscoveryData()

        tabLayoutDiscovery = activity!!.findViewById(R.id.tl_discovery_header)
        viewPagerDiscovery = activity!!.findViewById(R.id.vp_discovery_details)
    }

    override fun showCategory(categoryList: ArrayList<DiscoveryBean>) {
        categoryList.forEach {
            fragments.add(DiscoveryDetailsFragment(it.id))
            titles.add(it.name)
            tabLayoutDiscovery.addTab(tabLayoutDiscovery.newTab().setText(it.name))
        }
        Logger.d(titles.toArray())
        fragmentManager
        childFragmentManager?.let {
            adapter = MyPagerAdapter(
                it, FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT,
                fragments
            )
        }
        viewPagerDiscovery.adapter = adapter
        tabLayoutDiscovery.setupWithViewPager(viewPagerDiscovery)
        for (index in 0 until titles.count()) {
            tabLayoutDiscovery.getTabAt(index)!!.text = titles[index]
        }
    }

    override fun showError(errorMsg: String, errorCode: Int) {
    }

    override fun showLoading() {
    }

    override fun dismissLoading() {
    }
}